package ti.me.seek2chat.activities

import android.content.Intent
import android.os.Bundle
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import ti.me.seek2chat.databinding.ActivitySignInBinding
import ti.me.seek2chat.leancloud.LeanCloudService
import ti.me.seek2chat.utilities.Constants
import ti.me.seek2chat.utilities.PreferenceManager

/**
 * SignInActivity 是处理用户登录的活动类。
 *
 * 这个类负责处理用户输入的电子邮件和密码，并与 LeanCloud 后端进行交互以验证用户身份。
 */
class SignInActivity : AppCompatActivity() {
    private val binding by lazy { ActivitySignInBinding.inflate(layoutInflater) }
    private lateinit var preferenceManager: PreferenceManager
    private lateinit var leanCloudService: LeanCloudService

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root) // 视图绑定
        preferenceManager = PreferenceManager(applicationContext)
        if (preferenceManager.getBoolean(Constants.KEY_IS_SIGNED_IN)) {
            val intent = Intent(applicationContext, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(intent)
            finish()
        }
        leanCloudService = LeanCloudService(applicationContext)
        setListeners() // 绑定基本事件
    }

    /**
     * 事件绑定
     */
    private fun setListeners() {
        binding.textCreateNewAccount.setOnClickListener {
            val intent = Intent(this, SignUpActivity::class.java)
            startActivity(intent)
        }
        binding.buttonSignIn.setOnClickListener {
            if (isValidSignUpDetails()) {
                signIn()
            }
        }
    }

    /**
     * 用户登录操作
     */
    private fun signIn() {
        loading(true)
        val name = binding.inputName.text.toString().trim()
        val password = binding.inputPassword.text.toString().trim()
        leanCloudService.signIn(name, password) { success, user, errorMessage ->
            loading(false)
            if (success && user != null) {
                preferenceManager.putBoolean(Constants.KEY_IS_SIGNED_IN, true)
                preferenceManager.putString(Constants.KEY_USER_ID, user.objectId)
                preferenceManager.putString(Constants.KEY_NAME, user.username)
                preferenceManager.putString(Constants.KEY_EMAIL, user.email)
                user.getString("image")?.let {
                    preferenceManager.putString(Constants.KEY_IMAGE, it)
                }
                val intent = Intent(applicationContext, MainActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                showToast(errorMessage ?: "登录失败")
            }
        }
    }

    /**
     * 显示或隐藏加载进度条
     *
     * @param isLoading 是否正在加载
     */
    private fun loading(isLoading: Boolean) {
        if (isLoading) {
            binding.buttonSignIn.visibility = INVISIBLE
            binding.progressBar.visibility = VISIBLE
        } else {
            binding.buttonSignIn.visibility = VISIBLE
            binding.progressBar.visibility = INVISIBLE
        }
    }

    /**
     * 显示 Toast 消息
     *
     * @param message 消息内容
     */
    private fun showToast(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    /**
     * 验证用户输入的登录信息
     *
     * @return 输入是否有效
     */
    private fun isValidSignUpDetails(): Boolean {
        val name = binding.inputName.text.toString().trim()
        val password = binding.inputPassword.text.toString().trim()
        if (name.isEmpty()) {
            showToast("Please enter name")
            return false
        }  else if (password.isEmpty()) {
            showToast("Please enter password")
            return false
        } else {
            return true
        }
    }
}